package tool.workflow.fsSoft

import dao._
import implicits.Implicits._
import play.api.i18n.Messages
import shared.pojo.WorkflowMission.EachPlsdaData
import shared.tool.DefaultPickle
import tool.Pojo._
import tool.softT._
import tool.workflow.fsSoft.AllFsSoft.FSSoftBT
import tool._
import tool.plot._

import java.io.File
import scala.collection.immutable.SeqMap

/** Created by yz on 3/12/2020
  */
object FSPlsda extends FSSoftBT with PlsdaSoftBT {

  def produceSubConfigFile(workspaceDir: File, data: EachPlsdaData) = {
    val subConfigFile = new File(workspaceDir, "calculate_config.json")
    DefaultPickle.write(data).toFile(subConfigFile)
  }

  override def produceInput(workspaceDir: File, resultDir: File, index: Int, parentNodeStr: String, id: String)(implicit
      dao: MyDao,
      messages: Messages
  ): Unit = {
    val groupFile = new File(workspaceDir.getParentFile, "group.txt")
    val fsData = FeatureSelectionTool.getFsData(workspaceDir.getParentFile)
    groupFile.txtLines.lineSeqMap
      .filter { map =>
        fsData.plsda(index).groups.contains(map("ClassNote"))
      }
      .csvLines
      .toTxtFile(new File(workspaceDir, "group.txt"))
    FeatureSelectionTool.produceSubInputFile(workspaceDir, parentNodeStr)
    val data = FeatureSelectionTool.getFsData(workspaceDir.getParentFile).plsda(index)
    produceSubConfigFile(workspaceDir, data)
  }

  override def getCommandData(workspaceDir: File, resultDir: File, index: Int): List[CommandData] = {
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val groupFile = new File(workspaceDir, "group.txt")
    val command =
      s"""
         |${Tool.rScript} ${new File(
          Tool.rPath,
          "produce_sample_color.R"
        ).unixPath} --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath}
         |${Tool.rScript} ${Tool.rPath.unixPath}/fill_sample_color.R --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath} --pc ${plot.Plsda2D.plotO.configFileName}
         |${Tool.rScript} ${Tool.rPath.unixPath}/fill_sample_color.R --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath} --pc ${plot.Plsda3D.plotO.configFileName}
         |${Tool.rScript} ${Tool.rPath.unixPath}/fill_sample_color.R --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath} --pc ${plot.PlsdaBoxplot.plotO.configFileName}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "plsda_all_groups_calculate.R").unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "plsda_filter.R").unixPath}
           """.stripMargin
    val plotCommands = List(
      plot.Plsda2D.getCommand(workspaceDir, idStr = ""),
      plot.Plsda3D.getCommand(workspaceDir, idStr = ""),
      plot.PlsdaBoxplot.getCommand(workspaceDir, idStr = "")
    )
    List(CommandData(workspaceDir, List(command) ::: plotCommands))
  }

}
